<?php

namespace common\models;

use app\models\AdminLog;
use common\utils\XCache;
use Yii;

/**
 * This is the model class for table "post".
 *
 * @property string $id
 * @property string $title
 * @property string $catalog_id
 * @property string $recommend
 * @property string $sort
 * @property string $author
 * @property string $intro
 * @property string $face
 * @property string $photos
 * @property string $is_link
 * @property string $link
 * @property string $content
 * @property string $article_id
 * @property string $created_at
 * @property string $created_by
 * @property string $updated_at
 * @property string $updated_by
 * @property string $view_show
 * @property string $views
 */
class Post extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'post';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title'], 'required'],
            ['catalog_id', 'required', 'message' => '请选择所属栏目'],
            [['catalog_id', 'recommend', 'sort', 'article_id', 'created_at', 'created_by', 'updated_at', 'updated_by', 'views'], 'integer'],
            [['is_link', 'content'], 'string'],
            [['title'], 'string', 'max' => 128],
            [['author', 'view_show'], 'string', 'max' => 64],
            [['intro'], 'string', 'max' => 1000],
            [['link'], 'url', 'defaultScheme' => 'http'],
            ['sort', 'default', 'value' => 255],
            ['views', 'default', 'value' => 0],
            ['photos', 'safe'],
            [['face'], 'image', 'extensions' => 'jpeg, jpg, gif, png', 'maxSize' => 1 * 1024 * 1024]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => '标题',
            'catalog_id' => '所属栏目',
            'recommend' => '设置推荐',
            'sort' => '排序',
            'author' => '作者',
            'intro' => '摘要',
            'face' => '封面',
            'photos' => '组图',
            'is_link' => '展现方式：1为外链',
            'link' => '外链',
            'content' => '内容',
            'article_id' => '保存到素材',
            'created_at' => '创建时间',
            'created_by' => '添加人',
            'updated_at' => '更新时间',
            'updated_by' => '更新人',
            'view_show' => '内容视图',
            'views' => '浏览量',
        ];
    }

    public function attributeHints()
    {
        return ['sort' => '小的在前面', 'view_show' => '不选择默认为栏目内容视图'];
    }

    public function behaviors()
    {
        $path = '/uploads/image/' . date('Ymd') . '/p' . time() . '[[pk]].[[extension]]';
        return [
            [
                'class' => '\yiidreamteam\upload\ImageUploadBehavior',
                'attribute' => 'face',
                'filePath' => '@frontend/web' . $path,
                'fileUrl' => $path
            ],
        ];
    }

    /**
     * @return \common\models\Catalog
     */
    public function getCatalog()
    {
        return $this->hasOne(Catalog::className(), ['id' => 'catalog_id']);
    }

    /**
     * 内容属性
     * @return \yii\db\ActiveQuery
     */
    public function getAttr()
    {
        return $this->hasMany(PostAttr::className(), ['post_id' => 'id']);
    }

    public function beforeSave($insert)
    {
        if ($this->isNewRecord) {
            $this->created_at = $this->updated_at = time();
            $this->created_by = $this->updated_by = Yii::$app->user->id;
        } else {
            $this->updated_at = time();
            $this->updated_by = Yii::$app->user->id;
        }
        $this->sort < 1 && $this->sort = 1;
        if ($this->photos) {
            $this->photos = rtrim($this->photos, '|');
            $photos = explode('|', $this->photos);
            $this->photos = '';
            foreach ($photos as $photo) {
                if (file_exists(Yii::getAlias('@frontend/web') . $photo)) {
                    $this->photos = $this->photos . $photo . '|';
                }
            }
            $this->photos = rtrim($this->photos, '|');
        }
        return parent::beforeSave($insert);
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        if ($_FILES[$this->formName()]['name']['face']) {
            $this->face = $this->getImageFileUrl('face');
            $this->updateAll(['face' => $this->face], ['id' => $this->id]);
        }
        if ($insert) {
            AdminLog::log("新添内容：" . $this->title, "create");
        } else {
            @unlink(iconv('UTF-8', 'GB2312', Yii::$aliases['@frontend'] . '/web' . $changedAttributes['face']));
            AdminLog::log("更新内容：旧：" . $changedAttributes['title'] . "；新：" . $this->title);
        }
        XCache::postDelete($this->id);
    }

    public function afterDelete()
    {
        parent::afterDelete();
        @unlink(iconv('UTF-8', 'GB2312', Yii::$aliases['@frontend'] . '/web' . $this->face));
        AdminLog::log("删除内容：" . $this->title, "delete");
        XCache::postDelete($this->id);
    }

    /***
     * @param string $alias 栏目别名
     * @param int $number 数量
     * @param int $recommend 非0时只获取推荐
     * @return array 内容项
     */
    public static function items($alias, $number = 6, $recommend = 0)
    {
        /*$data = Post::find()->select("id,title,author,intro,face");
        //获取$catalogId子类
        $catalog = Catalog::findOne(['alias' => $alias]);
        if (!$catalog) {
            return [];
        }
        $childIdes = $catalog->getChildIdes($catalog->id);
        if ($childIdes) {
            $ids = $catalog->id . ',' . $childIdes;
            $data->where("catalog_id in($ids)");
        } else {
            $data->where("catalog_id=$catalog->id");
        }
        if ($recommend) {
            $data->andWhere("recommend=1");
        }
        $list = $data->orderBy("recommend desc,sort asc,id desc")->limit($number)->asArray()->all();
        foreach ((array)$list as $key => $item) {
            $list[$key]['url'] = \yii\helpers\Url::to(['/post', 'id' => $item['id']]);
        }
        return $list;*/
        return XCache::postItems($alias, $number, $recommend);
    }

    /**
     * 更新浏览量
     * @param $id
     * @return bool
     * @throws \yii\db\Exception
     */
    public static function viewUpdate($id)
    {
        //通过SESSION简单过虑刷新情况
        $session = Yii::$app->session;
        $preTime = $session->get('postViews_' . $id, 0);
        $time = time();
        if ($time - $preTime > 2) {//2=3-1秒
            $session->set('postViews_' . $id, $time);
            $sql = "update `post` set `views`=`views`+1 where id=" . $id;
            if (Yii::$app->db->createCommand($sql)->execute()) {
                return true;
            } else {
                return false;
            }
        }
    }
}
